<?php

namespace SisesporteAdmin\Controller;

use Zend\Mvc\Controller\AbstractActionController,
    Zend\View\Model\ViewModel;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Storage\Session as SessionStorage;
use SisesporteAdmin\Form\AuthForm,
    SisesporteAdmin\Form\EsqueciSenhaForm;
use Core\View\Helper\Criptografia;

/**
 * Objeto de controle de autenticação de usuário
 * 
 * @namespace SisesporteAdmin\Controller
 * 
 * @uses Zend\Mvc\Controller\AbstractActionController
 * @uses Zend\View\Model\ViewModel
 * @uses Zend\Authentication\AuthenticationService
 * @uses Zend\Authentication\Storage\Session as SessionStorag
 * @uses SisesporteAdmin\Form\AuthForm
 * @uses Zend\Mvc\Controller\AbstractActionController
 * @uses SisesporteAdmin\Form\EsqueciSenhaForm
 * 
 * @author ConfidereIT
 * @version 1.0.0
 */
class AuthController extends AbstractActionController
{

    /**
     * Método para logar o usuário
     * 
     * @access public
     * @param null
     * @return type
     */
    public function indexAction ()
    {
        $form = new AuthForm();
        $error = false;

        $request = $this->getRequest();
        
        $response = $this->getResponse();
//        $response->getHeaders()->addHeaderLine('Content-Type', "image/png");

        if ($request->isPost()) {
            $data = $request->getPost()->toArray();
            $form->setData($request->getPost());
            if ($form->isValid()) {

                $auth = new AuthenticationService();

                $sessionStorage = new SessionStorage("SisesporteAdmin");
                $auth->setStorage($sessionStorage);

                $authAdapter = $this->getServiceLocator()->get('Sisesporte\Auth\Adapter');

                $authAdapter->setNoLogin($data['noLogin'])
                        ->setNoSenha($data['noSenha']);

                $result = $auth->authenticate($authAdapter);
                $pessoa = $auth->getIdentity('user');

                if ($result->isValid()) {
                    $sessionStorage->write($auth->getIdentity('user'), null);
                    if ($pessoa[user]->inTipoPessoa == "A") {
                        $this->removeImageCaptcha($data[captcha][id]);
                        return $this->redirect()->toRoute("sisesporte-admin-interna", array(
                                    'controller' => 'aluno',
                                    'action' => 'view',
                                    'id' => $pessoa[user]->sqPessoa
                                )
                        );
                    } else {
                        $this->removeImageCaptcha($data[captcha][id]);
                        return $this->redirect()->toRoute("sisesporte-admin", array('controller' => 'aluno'));
                    }
                } else {
                    $this->removeImageCaptcha($data[captcha][id]);
                    $error = true;
                }
            }
            $this->removeImageCaptcha($data[captcha][id]);
        }
        
        $vielModel = new ViewModel(array('form' => $form, 'error' => $error));
        return $vielModel->setTerminal(true);
    }

    /**
     * Método de logout de usuário
     * 
     * @access public
     * @param null
     * @return Redirect
     */
    public function logoutAction ()
    {
        $auth = new AuthenticationService;
        $auth->setStorage(new SessionStorage('SisesporteAdmin'));
        $auth->clearIdentity();

        return $this->redirect()->toRoute('sisesporte-admin-auth');
    }

    /**
     * Método de resgate de senha do usuároi
     * 
     * @access public
     * @param null
     * @return ViewModel
     */
    public function esqueciSenhaAction ()
    {
        $form = new EsqueciSenhaForm();
        $error = null;

        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->getPost());
            if ($form->isValid()) {
                $data = $request->getPost()->toArray();
                $service = $this->getServiceLocator()->get('Sisesporte\Service\AuthService');
                
                $retorno = $service->esqueciSenha($data);
                
                $error = ($retorno) ? "success" : 'fail';
                
            }
        }

        $vielModel = new ViewModel(array('form' => $form, 'error' => $error));
        return $vielModel->setTerminal(true);
    }
    
    private function removeImageCaptcha($id)
    {
        $image = './data/captcha/' . $id . ".png";
            
        if (file_exists($image) == true) {
            unlink($image);
        }
    }

}
